<template>
  <div class="histories-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      title="浏览历史"
      left-arrow
      @click-left="$router.back()"
      fixed
    />
    <van-list
      v-if="user"
      class="historiesList"
      offset="20"
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <article-item
        v-for="(article, index) in list"
        :key="index"
        :article="article"
      />
    </van-list>
    <van-notice-bar
      class="noticeBar"
      v-else
      wrapable
      left-icon="volume-o"
      :scrollable="false"
      text="此功能归登录用户权限"
    />
  </div>
</template>

<script>
import { getHistoryAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem.vue'
import { mapState } from 'vuex'

export default {
  components: { ArticleItem },
  name: 'HistoryIndex',
  computed: {
    ...mapState(['user'])
  },
  data () {
    return {
      loading: false,
      finished: false,
      list: [],
      error: false,
      page: 1, // 当前页码
      per_page: 20 // 页码容量
    }
  },
  methods: {
    async onLoad () {
      this.loading = true
      try {
        // 1. 请求获取数据
        const { data } = await getHistoryAPI({
          page: this.page,
          per_page: this.per_page
        })
        // console.log(data)
        const { results } = data.data
        this.list.push(...results)
        this.loading = false

        this.page++

        // 4. 判断数据是否加载结束
        if (!results.length) {
          this.finished = true
        }

        // console.log(this.list.length)
      } catch (err) {
        console.log(err)
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.historiesList {
  padding-top: 100px;
}
.noticeBar {
  margin-top: 200px;
}
</style>
